package main

import (
	"flag"
	"fmt"
	"io/ioutil"
	"os"
	"os/exec"
	"strings"
)

var model string
var action string
var table string

func main() {
	flag.StringVar(&model, "m", "demo", "请输入模块名称")
	flag.StringVar(&action, "a", "create", "请设置操作")
	flag.StringVar(&table, "t", "", "要操作的表名")

	flag.Parse()

	dir, _ := os.Getwd()
	dir = strings.ReplaceAll(dir, `\`, `/`)
	println(dir)
	switch action {
	case "delete", "d":
		fileList := []string{
			fmt.Sprintf("/app/%s/auto/v1/%sApi.go", model, table),
			fmt.Sprintf("/app/%s/conf/auth/%s.go", model, table),
			fmt.Sprintf("/app/%s/conf/dict/%s.json", model, table),
			fmt.Sprintf("/app/%s/conf/orm/%sConfig.json", model, table),
			fmt.Sprintf("/app/%s/conf/preload/%sPreload.go", model, table),
			fmt.Sprintf("/app/%s/controller/admin/%sAdminController.go", model, table),
			fmt.Sprintf("/app/%s/migrate/%s_Migrate.go", model, table),
			fmt.Sprintf("/app/%s/models/%s_.go", model, table),
			fmt.Sprintf("/app/%s/models/%s_CURD.go", model, table),
			fmt.Sprintf("/app/%s/models/%s_Config.go", model, table),
			fmt.Sprintf("/app/%s/models/%s_Mod.go", model, table),
		}
		for _, s := range fileList {
			e := os.Remove(dir + s)
			if e != nil {
				println("文件移除错误", e.Error())
			}
		}
		break
	case "update", "u":

		content := fmt.Sprintf(`package main
import _ "api/app/%s/migrate"
func main() {}`, model)
		ioutil.WriteFile("var/tmp/update.go", []byte(content), 0777)
		cmd := exec.Command("go", "run", fmt.Sprintf(`%s/var/tmp/update.go`, dir))
		println(cmd.String())
		cmd.Stdout = os.Stdout
		cmd.Stderr = os.Stderr
		err := cmd.Run()
		if err != nil {
			println(err.Error())
		}
		//println(string(out))
		break
	default:

		content := fmt.Sprintf(`package main
			import _"api/app/%s/gen"
			func main() {println("OK")}`, model)
		ioutil.WriteFile("var/tmp/gen.go", []byte(content), 0777)
		cmd := exec.Command("go", "run", fmt.Sprintf(`%s/var/tmp/gen.go`, dir))
		cmd.Stdout = os.Stdout
		cmd.Stderr = os.Stderr
		err := cmd.Run()
		if err != nil {
			println(err.Error())
		}
	}

}
